//
//  AddAddressVC.m
//  phmall
//
//  Created by admin on 2017/12/11.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "AddAddressVC.h"
#import "EvaluateText.h"
#import "PlacePickerView.h"
@interface AddAddressVC ()<UITableViewDelegate,UITableViewDataSource>{
    UIView *headerView;
    UIImageView *background;
}
@property (nonatomic, strong) PlacePickerView *placePicker;
@property(strong,nonatomic)UITableView *myTableview;
@property(nonatomic,strong)UIView *nameView;
@property(nonatomic,strong)UILabel *nameLabel;
@property(nonatomic,strong)UITextField *name;
@property(nonatomic,strong)UIView *phoneView;
@property(nonatomic,strong)UILabel *phoneLabel;
@property(nonatomic,strong)UITextField *phone;
@property(nonatomic,strong)UIView *areaView;
@property(nonatomic,strong)UILabel *areaLabel;
@property(nonatomic,strong)UIButton *area;
@property(nonatomic,strong)UIView *streetView;
@property(nonatomic,strong)UILabel *streetLabel;
@property(nonatomic,strong)EvaluateText *street;
@property(nonatomic,strong)UIView *postalView;
@property(nonatomic,strong)UILabel *postalLabel;
@property(nonatomic,strong)UITextField *postal;
@property(nonatomic,strong)NSString *province;
@property(nonatomic,strong)NSString *city;
@property(nonatomic,strong)NSString *county;

@end

@implementation AddAddressVC
-(void)addAddress{
    if (self.name.text.length==0||self.name.text==nil) {
        [PublicClass ProgressHUDModeText:@"请填写收货人姓名" andTime:2 ];
        return;
    }
    if (self.phone.text.length==0||self.phone.text==nil) {
        [PublicClass ProgressHUDModeText:@"请填写收货人手机号" andTime:2 ];
        return;
    }
    if (self.street.text.length==0||self.street.text==nil) {
        [PublicClass ProgressHUDModeText:@"请填写收货人地址" andTime:2 ];
        return;
    }
    if (self.postal.text.length==0||self.postal.text==nil) {
        [PublicClass ProgressHUDModeText:@"请填写邮政编码" andTime:2 ];
        return;
    }
    if ((self.province.length==0||self.province==nil)&&(self.city.length==0||self.city==nil)&&(self.county.length==0||self.county==nil)) {
        [PublicClass ProgressHUDModeText:@"请选择地区" andTime:2 ];
        return;
    }
    
    
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"address_add/edit"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    if (self.model) {
        [parametersDic setObject:self.model.uid forKey:@"uid"];
    }
    [parametersDic setObject:self.name.text forKey:@"consignee"];
    [parametersDic setObject:self.street.text forKey:@"address"];
    [parametersDic setObject:self.postal.text forKey:@"zipcode"];
    [parametersDic setObject:self.phone.text forKey:@"mobile"];
    [parametersDic setObject:self.province forKey:@"province"];
    [parametersDic setObject:self.city forKey:@"city"];
    [parametersDic setObject:self.county forKey:@"county"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([response[@"ret"] isEqualToString:@"200"]) {
            [PublicClass ProgressHUDModeText:Localized(@"添加成功") andTime:2 ];
            if (self.delegate && [self.delegate respondsToSelector:@selector(reloadData)]) {
                [self.delegate reloadData];
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
        if ([response[@"ret"] isEqualToString:@"206"]) {
            [PublicClass ProgressHUDModeText:@"添加失败,地址已上限3条" andTime:2 ];
        }
        
    } andFailure:^{
        [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
    }];
}
-(void)selectAction{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    background.hidden=NO;
    [UIView animateWithDuration:0.5 animations:^{
        [self.placePicker mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.offset(0);
            make.bottom.offset(0);
            make.height.offset(250);
        }];
        [self.placePicker.superview layoutIfNeeded];
    }];
}
-(void)close{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    [UIView animateWithDuration:0.5 animations:^{
        [self.placePicker mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.offset(0);
            make.bottom.offset(250);
            make.height.offset(250);
        }];
        [self.placePicker.superview layoutIfNeeded];
    } completion:^(BOOL finished) {
        background.hidden=YES;
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.myTableview];
    
    [self.myTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(0);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).with.offset(self.tabBar_height-44);
    }];
    UIBarButtonItem* leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    
    self.navigationItem.leftBarButtonItem=leftBar;
   
    
    //整体界面
    headerView=[UIView new];
    headerView.backgroundColor=[UIColor groupTableViewBackgroundColor];

    self.nameView=[[UIView alloc]init];
    self.nameView.backgroundColor=[UIColor whiteColor];
    [headerView addSubview:self.nameView];
    [self.nameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(10);
        make.left.right.offset(0);
        make.height.offset(44);
    }];

    
    self.nameLabel=[[UILabel alloc]init];
    [self.nameView addSubview:self.nameLabel];
    self.nameLabel.text=Localized(@"收货人");
    self.nameLabel.font=[UIFont systemFontOfSize:15];
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(10);
    }];
    
    self.name=[[UITextField alloc]init];
    [self.nameView addSubview:self.name];
    self.name.placeholder=Localized(@"收货人");
    self.name.textColor=[UIColor colorWithHexString:@"#adadad"];
    self.name.textAlignment=NSTextAlignmentRight;
    self.name.font=[UIFont systemFontOfSize:15];
    [self.name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.width.offset(SCREEN_WIDTH-90);
        make.left.offset(80);
    }];
    
    
    self.phoneView=[[UIView alloc]init];
    self.phoneView.backgroundColor=[UIColor whiteColor];
    [headerView addSubview:self.phoneView];
    [self.phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nameView.mas_bottom).offset(1);
        make.left.right.offset(0);
        make.height.offset(44);

    }];

    self.phone=[[UITextField alloc]init];
    [self.phoneView addSubview:self.phone];
    self.phone.placeholder=Localized(@"手机号码");
    self.phone.textColor=[UIColor colorWithHexString:@"#adadad"];
    self.phone.textAlignment=NSTextAlignmentRight;
    self.phone.font=[UIFont systemFontOfSize:15];
    [self.phone mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.width.offset(SCREEN_WIDTH-90);
        make.left.offset(80);
    }];

    self.phoneLabel=[[UILabel alloc]init];
    [self.phoneView addSubview:self.phoneLabel];
    self.phoneLabel.text=Localized(@"手机号码");

    self.phoneLabel.font=[UIFont systemFontOfSize:15];
    [self.phoneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(10);
//        make.right.equalTo(self.phone.mas_left).offset(-10);
    }];

    self.areaView=[[UIView alloc]init];
    self.areaView.backgroundColor=[UIColor whiteColor];
    [headerView addSubview:self.areaView];
    [self.areaView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneView.mas_bottom).offset(1);
        make.left.right.offset(0);
        make.height.offset(44);

    }];

    self.area=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.areaView addSubview:self.area];
    [self.area setTitle:Localized(@"请选择") forState:UIControlStateNormal];
    [self.area setImage:[UIImage imageNamed:@"前往"] forState:UIControlStateNormal];
    [self.area setTitleColor:[UIColor colorWithHexString:@"adadad"] forState:UIControlStateNormal];
    self.area.titleLabel.font=[UIFont systemFontOfSize:13];
    [self.area mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.right.offset(-10);
    }];
    [self.area addTarget:self action:@selector(selectAction) forControlEvents:UIControlEventTouchUpInside];
    [self.area layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:5];

    self.areaLabel=[[UILabel alloc]init];
    [self.areaView addSubview:self.areaLabel];
    self.areaLabel.text=Localized(@"所属地区");

    self.areaLabel.font=[UIFont systemFontOfSize:15];
    [self.areaLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(10);
//        make.right.equalTo(self.area.mas_left).offset(-10);
    }];

    self.streetView=[[UIView alloc]init];
    self.streetView.backgroundColor=[UIColor whiteColor];
    [headerView addSubview:self.streetView];
    [self.streetView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.areaView.mas_bottom).offset(1);
        make.left.right.offset(0);
        make.height.offset(60);

    }];

    //
    self.streetLabel=[[UILabel alloc]init];
    [self.streetView addSubview:self.streetLabel];
    self.streetLabel.text=Localized(@"街道地址");
    self.streetLabel.font=[UIFont systemFontOfSize:15];
    [self.streetLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(12);
        make.left.offset(10);
        //        make.right.equalTo(self.street.mas_left).offset(-10);
    }];
    
    CGSize size = [self.streetLabel.text boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil].size;
    
    self.street=[[EvaluateText alloc]init];
    [self.streetView addSubview:self.street];
    self.street.textColor=[UIColor colorWithHexString:@"#adadad"];
    self.street.placeholder=Localized(@"填写详细地址");
    self.street.font=[UIFont systemFontOfSize:13];
    [self.street mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(4);
        make.bottom.offset(-4);
        make.width.offset(SCREEN_WIDTH-size.width-30);
        make.right.offset(-10);
    }];


    self.postalView=[[UIView alloc]init];
    self.postalView.backgroundColor=[UIColor whiteColor];
    [headerView addSubview:self.postalView];
    [self.postalView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.streetView.mas_bottom).offset(1);
        make.left.right.offset(0);
        make.height.offset(44);
        make.bottom.equalTo(headerView.mas_bottom).with.offset(-0).priorityHigh();
    }];

    self.postal=[[UITextField alloc]init];
    [self.postalView addSubview:self.postal];
    self.postal.placeholder=Localized(@"邮政编码");
    self.postal.textColor=[UIColor colorWithHexString:@"#adadad"];
    self.postal.textAlignment=NSTextAlignmentRight;
    self.postal.font=[UIFont systemFontOfSize:15];
    [self.postal mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.width.offset(SCREEN_WIDTH-70);
        make.right.offset(-10);
    }];

    self.postalLabel=[[UILabel alloc]init];
    [self.postalView addSubview:self.postalLabel];
    self.postalLabel.text=Localized(@"邮政编码");

    self.postalLabel.font=[UIFont systemFontOfSize:15];
    [self.postalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(10);
//        make.right.equalTo(self.postal.mas_left).offset(-10);
    }];


    //添加webview前计算一次高度
    CGFloat height = [headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    CGRect frame = headerView.bounds;
    frame.size.height = height;
    headerView.frame = frame;
    [self.myTableview setTableHeaderView:headerView];
    [headerView layoutIfNeeded];
    
    
    UIButton* addAddress=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:addAddress];
    [addAddress setTitle:Localized(@"保存") forState:UIControlStateNormal];
    [addAddress addTarget:self action:@selector(addAddress) forControlEvents:UIControlEventTouchUpInside];
    [addAddress setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    addAddress.backgroundColor=[UIColor colorWithHexString:@"#52C1BA"];
    //    [logOut setBackgroundImage:[UIImage imageNamed:@"背景渐变条"] forState:UIControlStateNormal];
    [addAddress mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(49);
        make.bottom.equalTo(self.view).offset(-self.tabBar_height);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view.mas_right);
    }];
    
    background=[UIImageView new];
    background.image=[UIImage imageNamed:@"透明图片"];
    [[UIApplication sharedApplication].keyWindow addSubview:background];
    [background mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.offset(0);
    }];
    background.hidden=YES;
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(close)];
    background.userInteractionEnabled=YES;
    [background addGestureRecognizer:tap];
    
    __weak __typeof(self)weakSelf = self;
    self.placePicker = [[PlacePickerView alloc] initWithIsRecordLocation:YES SendPlaceArray:^(NSArray *placeArray) {
        NSLog(@"省:%@ 市:%@ 区:%@",placeArray[0],placeArray[1],placeArray[2]);
        [weakSelf.area setTitle:[NSString stringWithFormat:@"%@  %@  %@",placeArray[0],placeArray[1],placeArray[2]] forState:UIControlStateNormal];
        [self.area layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:5];
        self.province=placeArray[0];
        self.city=placeArray[1];
        self.county=placeArray[2];
        [weakSelf close];
    }];
    self.placePicker.cancelBlock = ^{
        [weakSelf close];
    };
    [background addSubview:self.placePicker];
    [self.placePicker mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.bottom.offset(250);
        make.height.offset(250);
    }];
    [self.placePicker.superview layoutIfNeeded];
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    if (self.model!=nil) {
        self.name.text=self.model.consignee;
        [weakSelf.area setTitle:[NSString stringWithFormat:@"%@  %@  %@",self.model.province,self.model.city,self.model.county] forState:UIControlStateNormal];
        [self.area layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:5];
        
        self.province=self.model.province;
        self.city=self.model.city;
        self.county=self.model.county;
        
        self.phone.text=self.model.mobile;
        self.street.text=self.model.address;
        self.postal.text=self.model.zipcode;
    }
    // Do any additional setup after loading the view.
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 0;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    //总高度
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"newCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;;
    }
    cell.opaque=YES;
    cell.layer.drawsAsynchronously=YES;
    cell.layer.rasterizationScale=[UIScreen mainScreen].scale;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    //分割线补全
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

//MARK:-GETTER
- (UITableView *)myTableview{
    if (!_myTableview) {
        _myTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableview.delegate = self;
        _myTableview.dataSource = self;
        _myTableview.backgroundColor=[UIColor groupTableViewBackgroundColor];
        _myTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTableview.showsVerticalScrollIndicator=NO;
        _myTableview.scrollEnabled = YES;
    }
    return _myTableview;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
